package gitee

import (
	"strings"
)

const baseSuffix = ".git"

func filterPathNode(pv ...string) string {
	var sb strings.Builder
	var size int

	for _, v := range pv[:len(pv)-1] {
		if !IsPathReachable(v) {
			return ""
		}
		size += len(v) + 1
	}

	path := strings.TrimSuffix(pv[len(pv)-1], baseSuffix)

	size += len(path)
	sb.Grow(size)

	for _, v := range pv[:len(pv)-1] {
		sb.WriteString(v)
		sb.WriteString("/")
	}

	sb.WriteString(path)

	return sb.String()
}

// IsPathReachable path reachable
func IsPathReachable(s string) bool {
	return s != "." && s != ".."
}

// PathNodeCanonicalizeStrict todo
func PathNodeCanonicalizeStrict(u string) string {
	pvv := StrSplitSkipEmpty(u, '/', 64)
	if len(pvv) < 2 {
		return ""
	}

	return filterPathNode(pvv...)
}

// PathNodeCanonicalize todo
func PathNodeCanonicalize(u string) string {
	pv := PathSplit(u, 64)
	if len(pv) < 2 {
		return ""
	}

	return filterPathNode(pv...)
}
